<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        :defaultConfig="editorConfig"
        v-model="valueHtml"
        mode="default"
        @onCreated="handleCreated"
    />
  </div>
</template>
<script setup lang="ts">
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import {onBeforeUnmount, ref, shallowRef, watch, watchEffect} from "vue"
import {IEditorConfig} from '@wangeditor/editor'
import {BASE_UPLOAD_FILE} from "@/axios";
import type {AxiosResponse} from "axios";
import {message} from "ant-design-vue";
import type {TooltipAlignConfig} from "ant-design-vue/es/tooltip";
import {IDomEditor} from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';

const emit = defineEmits(["setValueHtml"]);
const props = defineProps(["content"])

// 获取编辑器实例
const editorRef = shallowRef();

// 内容
const valueHtml = ref<string>("");

// 初始化
const editorConfig: Partial<IEditorConfig> | any = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

// 工具栏
const toolbarConfig: TooltipAlignConfig | any = {}

// 工具栏,禁止上传视频
toolbarConfig.excludeKeys = [
  "group-video"
]

// 设置图片上传
editorConfig.MENU_CONF['uploadImage'] = {
  // 上传地址
  server: BASE_UPLOAD_FILE,
  // 配置请求体字段名
  fieldName: 'file',
  // 上传图片处理请求判断
  customInsert(r: AxiosResponse, insertFn: (url: string) => void) {
    // 成功
    if (r.data.code >= 200 && r.data.code < 300) {
      insertFn(r.data.data.path);
    } else {
      message.error('上传图片失败');
    }
  }
}

// 组件销毁时，即使销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 传给父组件
watch(valueHtml, (newV) => {
  emit('setValueHtml', newV);
})
watchEffect(() => {
  if (props.content) {
    valueHtml.value = props.content;
  }
})
</script>